/*

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yufei.toolinterface;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yufei.infoExtractor.core.InfoExtractorMI;
import com.yufei.infoExtractor.core.impl.InfoExtractorM;
import com.yufei.infoExtractor.pfw.entity.Entity;
import com.yufei.infoExtractor.util.AnnotationUtil;
import com.yufei.infoExtractor.util.AppUtil;
import com.yufei.infoExtractor.util.ExceptionUtil;
import com.yufei.toolinterface.util.ComponentFactory;
import com.yufei.toolinterface.util.DialogUtil;
import com.yufei.toolinterface.util.TableModelUtil;

/**
 *
 * @author Administrator
 */
@SuppressWarnings("serial")
public class InfoSearch extends javax.swing.JDialog {
	private static Log mLog = LogFactory.getLog(InfoExtractorM.class);

private InfoExtractorMI infoExtractorMI=(InfoExtractorMI) AppUtil.getBeanFromBeanContainer(InfoExtractorM.class);
    /**
     * Creates new form InfoSearch
     */
private 	List<Entity>  resultList=null;
String collectionName0=null;

  
	public String getCollectionName0() {
	return collectionName0;
}

public void setCollectionName0(String collectionName0) {
	this.collectionName0 = collectionName0;
}

	public InfoSearch(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        List<String> classFullNames=infoExtractorMI.getAllEntityFullClassName();
        for(String className:classFullNames){
        	this.collectionName.addItem(className);
        }
        this.collectionName.setEditable(true);
        collectionName.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) {
				// TODO Auto-generated method stub
				itemStateChangedListener(e);
			}
		});
    }
private void itemStateChangedListener(ItemEvent e){
	//只响应一次事件
	if(e.getStateChange()==1){
		JComboBox jComboBox=((JComboBox)e.getSource());
		String className=jComboBox.getSelectedItem().toString() ;
		try {
			Class entityClass=Class.forName(className);
			List<String> fieldNames=AnnotationUtil.getQueryEnableFieldNames(entityClass);
			queryPanel.add(ComponentFactory.createFieldQueryJPanle(fieldNames));
			queryPanel.setPreferredSize(new Dimension(100, 30));
			this.invalidate();
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
	    DialogUtil.popUpDialog("类名有误");
		}	
	}
	
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        recordsNumber = new javax.swing.JTextField();
        queryButton = new java.awt.Button();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        collectionName = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        addButton = new javax.swing.JButton();
        exportButton = new javax.swing.JButton();
        exportPath = new javax.swing.JTextField();
        queryPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("信息查询");

        jLabel1.setText("表名");

        jLabel2.setText("查询记录数");

        recordsNumber.setText("100");
        recordsNumber.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recordsNumberActionPerformed(evt);
            }
        });

        queryButton.setLabel("query");
        queryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                queryButtonActionPerformed(evt);
            }
        });

        jTable1.setPreferredSize(new java.awt.Dimension(0, 500));
        jScrollPane1.setViewportView(jTable1);

        collectionName.setEditable(true);
        collectionName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                collectionNameActionPerformed(evt);
            }
        });

        jLabel3.setText("总数");

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Delete");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        exportButton.setText("Export To");
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        exportPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportPathActionPerformed(evt);
            }
        });
        queryPanel.setLayout(new FlowLayout());
        javax.swing.GroupLayout queryPanelLayout = new javax.swing.GroupLayout(queryPanel);
        queryPanel.setLayout(queryPanelLayout);
        queryPanelLayout.setHorizontalGroup(
            queryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        queryPanelLayout.setVerticalGroup(
            queryPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 24, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(exportButton)
                .addGap(28, 28, 28)
                .addComponent(exportPath, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 23, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(collectionName, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(recordsNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(queryButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(queryPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(queryButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(recordsNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(collectionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(queryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(deleteButton)
                    .addComponent(addButton)
                    .addComponent(exportButton)
                    .addComponent(exportPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public List<Entity> getResultList() {
		return resultList;
	}

	public void setResultList(List<Entity> resultList) {
		this.resultList = resultList;
	}

	private void collectionNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_collectionNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_collectionNameActionPerformed

    private void recordsNumberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recordsNumberActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_recordsNumberActionPerformed

    private void queryButtonActionPerformed(java.awt.event.ActionEvent evt)  {//GEN-FIRST:event_queryButtonActionPerformed
        // TODO add your handling code here:
		collectionName0 = this.collectionName.getSelectedItem().toString();

		try {
		resultList=(List<Entity>) infoExtractorMI.queryEntity(collectionName0);
		this.recordsNumber.setText(String.valueOf(resultList.size()));
		Class elementType=Class.forName(collectionName0);
		jTable1=ComponentFactory.createJTableForCollectionInformation(this, resultList,elementType);
		 jScrollPane1.setViewportView(jTable1);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
     
    		/*try {
    			collectionName0 = this.collectionName.getSelectedItem().toString();
				List<Entity> resultList=(List<Entity>) infoExtractorMI.queryEntity(collectionName0);
				
				AbstractTableModel tableModel = TableModelUtil.getTableModel(Class.forName(collectionName0));

				int rowNumber=0;
				Vector<Object> vector=null;
				try {
					Object[] results=CommonUtil.sort(resultList.toArray());
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					DialogUtil.popUpDialog(e1.getMessage());
				}
				for(Object  entity:resultList){
					try {
						vector=TableModelUtil.convertEntityToVector( entity,tableModel);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						mLog.debug(entity.toString()+";转换成row出现错误！");
						//DialogUtil.popUpDialog(entity.toString()+";转换成row出现错误！");
					} 
					//将entity 装换成正确的vector
					((DefaultTableModel)tableModel).insertRow(rowNumber, vector);

				}
				jTable1.setModel(tableModel);
				
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				DialogUtil.popUpDialog("找不到类："+collectionName0);
				
			}*/
    }//GEN-LAST:event_queryButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
     
  
		try {
			resultList=TableModelUtil.convertVectorToEntity(Class.forName(collectionName0),(DefaultTableModel)jTable1.getModel());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    	for(Entity entity:resultList){
    		infoExtractorMI.saveObject(entity);
    	}
		DialogUtil.popUpDialog("保存成功！");

    }//GEN-LAST:event_jButton1ActionPerformed

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        // TODO add your handling code here:
    	//add a blank row then the user can edit it then click save button to persist into database
    DefaultTableModel defaultTableModel=	(DefaultTableModel) jTable1.getModel();
    try {
		defaultTableModel.addRow(TableModelUtil.convertEntityToVector(Class.forName(collectionName0).newInstance(), defaultTableModel));
	} catch (Exception e) {
		// TODO Auto-generated catch block
		mLog.info(ExceptionUtil.getExceptionDetailsMessage(e));
	} 

    }//GEN-LAST:event_addButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        // TODO add your handling code here:
    	int[] selectedRows=jTable1.getSelectedRows();
    	
	
		


    	List<Entity> deleteList=new ArrayList<Entity>();
    	DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		for(int deleteRow:selectedRows){
    		deleteList.add(TableModelUtil.convertTableRowToEntity(resultList.get(0).getClass(), model, deleteRow));
    	}
		for(Entity entity:deleteList){
    		infoExtractorMI.deleteObject(entity);
    	}
		for(int selectedRow:selectedRows){
			  ((DefaultTableModel)model).removeRow(selectedRow);

		}
		DialogUtil.popUpDialog("删除成功！");
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void exportPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportPathActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_exportPathActionPerformed

    private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
        // TODO add your handling code here:
    	String exportPath=this.exportPath.getText().trim();
    	if(exportPath==null){
return;
    	}
 //   	infoExtractorMI.exportTaskToXml(taskName, path);
    }//GEN-LAST:event_exportButtonActionPerformed

    /**
	 * @param entity
	 * @return
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
	 */


	/**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(InfoSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(InfoSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(InfoSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(InfoSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                InfoSearch dialog = new InfoSearch(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JComboBox collectionName;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton exportButton;
    private javax.swing.JTextField exportPath;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private java.util.List list1;
    private java.awt.Button queryButton;
    private javax.swing.JPanel queryPanel;
    private javax.swing.JTextField recordsNumber;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}
